package com.itheima.wisdomnext.controller;

import com.itheima.wisdomnext.entity.Administrator;
import com.itheima.wisdomnext.entity.Result.ResponseResult;
import com.itheima.wisdomnext.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AuthService authService;

    // 管理员注册
    @PostMapping("/register")
    public ResponseEntity<ResponseResult<Map<String, Object>>> register(@RequestBody Administrator administrator) {
        authService.registerAdministrator(administrator);
        // 创建响应数据
        Map<String, Object> responseData = new HashMap<>();
        return ResponseEntity.ok(ResponseResult.success("管理员注册成功", responseData));
    }

    // 管理员登录
    @PostMapping("/login")
    public ResponseEntity<ResponseResult<Map<String, Object>>> login(@RequestBody Administrator administrator) {
        String loginResult = authService.loginAdministrator(administrator);

        // 处理 loginResult，提取 token 和 adminId
        String[] parts = loginResult.split(", ");
        String token = parts[0].split(": ")[1];
        String adminId = parts[1].split(": ")[1];

        // 创建响应数据
        Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("adminId", adminId);
        return ResponseEntity.ok(ResponseResult.success("管理员登录成功", responseData));
    }
}
